package com.ux.iot.jetlinks.config;

import com.alibaba.fastjson.JSON;
import com.ux.iot.core.service.IotMsgService;
import com.ux.iot.jetlinks.contant.JetlinksContants;
import com.ux.iot.jetlinks.pro.JetlinksProperties;
import com.ux.iot.jetlinks.service.product.ProductService;
import com.ux.iot.jetlinks.service.product.imp.ConfigProductService;
import com.ux.iot.jetlinks.service.sub.ProductLevelSub;
import com.ux.iot.jetlinks.service.sub.request.ServiceInfo;
import com.ux.iot.jetlinks.service.sub.subscribe.SampleProductSubscribe;
import com.ux.iot.jetlinks.service.websocket.JetlinksConnectListener;
import com.ux.iot.jetlinks.service.websocket.SingleEndPointAsyncIotMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author caixiaodao
 * @version 1.0
 * 功能描述
 * 自动订阅处理
 * @date 2021/11/16 13:19
 */
@Slf4j
@EnableConfigurationProperties(JetlinksProperties.class)
@ConditionalOnProperty(prefix = JetlinksContants.PRO_PREFIX,name = "auto-sub",havingValue = "true")
public class JetlinksSubAutoConfigure {
    @Autowired
    ServiceInfo subRequestIdPro;
    @Autowired
    JetlinksProperties pro;
    @PostConstruct
    public  void  init(){
        log.info("自动订阅开启 服务器信息{},", JSON.toJSONString(subRequestIdPro));
    }


    @Bean("productSubscribe")
    @ConditionalOnMissingBean(ProductLevelSub.class)
    public SampleProductSubscribe subscribe(ProductService productService, SingleEndPointAsyncIotMsgService singleEndPointAsyncIotMsgService){
        return  new SampleProductSubscribe(productService,subRequestIdPro,singleEndPointAsyncIotMsgService);
    }
    @Bean("listeners")
    public List<JetlinksConnectListener> getListeners(JetlinksConnectListener... subscribe){
        List<JetlinksConnectListener> listeners =new ArrayList<>();
        listeners.addAll(Arrays.asList(subscribe));
        return  listeners;
    }

    @Bean("productService")
    @ConditionalOnMissingBean(ProductService.class)
    public ConfigProductService configProductService(){
        return  new ConfigProductService(pro.getProduct());
    }
    @Bean("singleEndPointAsyncIotMsgService")
    @ConditionalOnMissingBean(IotMsgService.class)
    public SingleEndPointAsyncIotMsgService singleEndPointAsyncIotMsgService(){
        return  new SingleEndPointAsyncIotMsgService();
    }
}
